<template>
  <div id="menu">
    <a-menu @select="select"
            :openKeys.sync="openKeys"
            v-model="selectedKeys"
            mode="inline"
            :inline-collapsed="collapsed"
            :class="collapsed ? 'fold' : 'unfold'">
      <s-sub-menu v-for="menu in data"
                  :key="menu.key"
                  :menu-info="menu" />
    </a-menu>
  </div>
</template>

<script>
import SSubMenu from "@/components/SSubMenu";

export default {
  name: "SMenu",
  props: ["data", "collapsed"],
  components: { SSubMenu },
  data () {
    return {
      openKeys: [],
      selectedKeys: []
    };
  },
  watch: {
    $route: {
      handler () {
        if (!this.data.length) {
          return;
        }

        if (this.getTargetMenu()) {
          // 如果不同则更新，防止用户使用浏览器的历史操作按钮引发死循环
          const targetKeys = this.getTargetMenu().idPath;

          if (
            this.selectedKeys[this.selectedKeys.length - 1] !==
            targetKeys[targetKeys.length - 1]
          ) {
            this.selectedKeys = [...targetKeys];
            this.openKeys = [...this.selectedKeys];
          }
        } else {
          this.selectedKeys = [];
          this.openKeys = [];
        }
      }
    },
    data: {
      handler () {
        if (this.data.length) {
          if (this.getTargetMenu()) {
            this.selectedKeys = this.getTargetMenu().idPath;
            this.openKeys = [...this.selectedKeys];
          } else {
            this.openKeys = [];
          }
        }
      },
      immediate: true
    }
  },
  computed: {
    menuList () {
      const obj = {};

      const fn = (node, parentIds) => {
        obj[node.key] = {
          ...node,
          idPath: [...parentIds, node.key],
          children: node.children
            ? node.children.map((item) => fn(item, [...parentIds, node.key]))
            : node.children
        };
      };
      this.data.forEach((node) => fn(node, []));
      return obj;
    }
  },
  methods: {
    getTargetMenu () {
      return Object.values(this.menuList).filter(
        (item) => this.$route.matched.filter(match => match.regex.test(item.path) || match.regex.test("/" + item.path)).length
      )[0];
    },
    select ({ key }) {
      this.$router
        .push(
          (/^\//.test(this.menuList[key].path) ? "" : "/") +
          this.menuList[key].path
        )
        .catch(() => {
        });
    }
  }
}
  ;
</script>

<style lang="scss" scoped>
#menu {
  height: 100%;
  overflow-y: auto;
  .unfold {
    width: 256px;
  }
  .fold {
    width: auto;
  }
  ::v-deep .ant-menu-inline-collapsed > .ant-menu-submenu > .ant-menu-submenu-title {
    left: 0;
    padding: 0px 20px !important;
    text-overflow: clip;
  }
  ::v-deep .ant-menu-inline-collapsed > .ant-menu-item{
    left: 0;
    padding: 0px 20px !important;
    text-overflow: clip;
  }
}
</style>
